package com.study.demo.data.remote;


import com.study.demo.api.forum.ForumApi;
import com.study.demo.bean.Forums;
import com.study.demo.bean.ForumsData;
import com.study.demo.bean.ForumsResult;
import com.study.demo.bean.MyForumsData;
import com.study.demo.bean.MyForumsResult;
import com.study.demo.data.ForumDataSource;
import com.study.demo.db.Forum;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;

/**
 * Created by sll on 2016/6/3.
 */
public class ForumRemoteDataSource implements ForumDataSource {

    private final ForumApi mForumApi;
    private String forumId;

    @Inject
    public ForumRemoteDataSource(ForumApi mForumApi) {
        this.mForumApi = mForumApi;
    }

    @Override
    public Observable<List<Forum>> getForumList(final String forumId) {
        this.forumId = forumId;
        if (forumId.equals("0")) {
            return mForumApi.getMyForums().map(this::convertToForums).

                    onErrorReturn(this::onErrorReturn);
        } else {
            return mForumApi.getForums().map(this::convertToForums2)
                    .onErrorReturn(this::onErrorReturn);
        }
    }

    private List<Forum> convertToForums(MyForumsData forumsData) {
        if (forumsData != null && forumsData.data != null) {
            MyForumsResult data = forumsData.data;
            for (Forum forum : data.sub) {
                forum.setForumId(data.fid);
                forum.setCategoryName(data.name);
                forum.setWeight(1);
            }
            return data.sub;
        }
        return null;
    }

    private List<Forum> convertToForums2(ForumsData forumsData) {
        if (forumsData != null) {
            List<Forum> forumList = new ArrayList<>();
            for (ForumsResult data : forumsData.data) {
                if (data.fid.equals(forumId)) {
                    for (Forums forums : data.sub) {
                        for (Forum forum : forums.data) {
                            forum.setForumId(data.fid);
                            forum.setCategoryName(forums.name);
                            forum.setWeight(forums.weight);
                            forumList.add(forum);
                        }
                    }
                }
            }
            return forumList;
        }
        return null;
    }

    private List<Forum> onErrorReturn(Throwable throwable) {
        return null;
    }


    @Override
    public Observable<Boolean> removeForum(String fid) {
        return null;
    }
}
